<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">






  
  
  <link rel="stylesheet" media="all" href="/lib/Han/dist/han.min.css?v=3.3">




<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.png?v=5.1.4">


  <link rel="mask-icon" href="/images/favicon.png?v=5.1.4" color="#222">





  <meta name="keywords" content="面试题目," />





  <link rel="alternate" href="/atom.xml" title="平步青云win" type="application/atom+xml" />






<meta name="description" content="leetcode是个题库，里面有很编程多面试的题目，可以在线编译运行。难度比较高。如果自己能都做出来，对面大公司很有帮助。">
<meta name="keywords" content="面试题目">
<meta property="og:type" content="article">
<meta property="og:title" content="LeetCode算法题目">
<meta property="og:url" content="https://zxpgo.github.io/2018/08/22/LeetCode算法题目/index.html">
<meta property="og:site_name" content="平步青云win">
<meta property="og:description" content="leetcode是个题库，里面有很编程多面试的题目，可以在线编译运行。难度比较高。如果自己能都做出来，对面大公司很有帮助。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://i.imgur.com/tuXJeop.gif">
<meta property="og:image" content="https://i.imgur.com/NkFDJCn.png">
<meta property="og:image" content="https://i.imgur.com/RRuWyQ4.png">
<meta property="og:updated_time" content="2019-02-12T14:03:28.583Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="LeetCode算法题目">
<meta name="twitter:description" content="leetcode是个题库，里面有很编程多面试的题目，可以在线编译运行。难度比较高。如果自己能都做出来，对面大公司很有帮助。">
<meta name="twitter:image" content="https://i.imgur.com/tuXJeop.gif">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"right","display":"post","offset":10,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: 'PAO8LM7QB1',
      apiKey: '',
      indexName: 'Blog',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zxpgo.github.io/2018/08/22/LeetCode算法题目/"/>





  <title>LeetCode算法题目 | 平步青云win</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?7a4517a3ce6d7c50203655d056f01ac3";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">平步青云win</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description"></h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-随笔">
          <a href="/sui" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            随笔
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
			
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zxpgo.github.io/2018/08/22/LeetCode算法题目/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zxp">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="平步青云win">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">LeetCode算法题目</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-08-22T22:28:50+08:00">
                2018-08-22
              </time>
            

            

            
          </span>

          

          
            
          

          
          
             <span id="/2018/08/22/LeetCode算法题目/" class="leancloud_visitors" data-flag-title="LeetCode算法题目">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body han-init-context" itemprop="articleBody">

      
      

      
        <p>leetcode是个<a href="https://leetcode-cn.com/problemset/all/" target="_blank" rel="noopener">题库</a>，里面有很编程多面试的题目，可以在线编译运行。难度比较高。如果自己能都做出来，对面大公司很有帮助。<a id="more"></a></p>
<h2 id="两数之和"><a href="#两数之和" class="headerlink" title="两数之和"></a>两数之和</h2><p>给定一个整数数组和一个目标值，找出数组中和为目标值的两个数。</p>
<p>你可以假设每个输入只对应一种答案，且同样的元素不能被重复利用。</p>
<p><strong>示例：</strong></p>
<pre><code>给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
</code></pre><p><strong>思路：</strong></p>
<p>利用python实现，先将列表转化为字典dict1，字典的键为列表元素，字典的值为对应元素的下标。</p>
<p>对于每个元素nums[i]，对于给定的target数，检查字典中是否有键（target-nums[i]）,如果存在则说明，该键对应的值和nums[i]的下标为对应的输出结果。注意该键对应的值不能是i!</p>
<p><strong>代码：</strong></p>
<pre><code>class Solution:
    def twoSum(self, nums, target):
        &quot;&quot;&quot;
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        &quot;&quot;&quot;
        dict1 = {}
        l = len(nums)
        for i in range(0,l):
            dict1[nums[i]] = i
        for i in range(0,l):
            temp = target - nums[i]
            if (temp in dict1.keys()) and dict1.get(temp) != i:
                return [i,dict1.get(temp)]
</code></pre><p><strong>算法分析:</strong></p>
<p>时间复杂度：O(n)， 我们把包含有 nn 个元素的列表遍历两次。由于哈希表将查找时间缩短到 O(1)O(1) ，所以时间复杂度为 O(n)O(n)。</p>
<p>空间复杂度：O(n)， 所需的额外空间取决于哈希表中存储的元素数量，该表中存储了 nn 个元素。 </p>
<h2 id="两数相加"><a href="#两数相加" class="headerlink" title="两数相加"></a>两数相加</h2><p>给定两个非空链表来表示两个非负整数。位数按照逆序方式存储，它们的每个节点只存储单个数字。将两数相加返回一个新的链表。</p>
<p>你可以假设除了数字 0 之外，这两个数字都不会以零开头。</p>
<p><strong>示例：</strong></p>
<pre><code>输入：(2 -&gt; 4 -&gt; 3) + (5 -&gt; 6 -&gt; 4)
输出：7 -&gt; 0 -&gt; 8
原因：342 + 465 = 807
</code></pre><p><strong>思路：</strong></p>
<p>考虑到两个链表长度不一，短的列表后面补零。</p>
<p>最开始的创建一个链表（ll），并赋值一个另一个值(lp)（后面链表的指针需要移动，不指向起始），并创建一个变量来存储进位的值（temp）。</p>
<p>首先判读两个链表是否都已到达末尾，如果没有，将两个链表的值分别赋值给两个变量（val1和val2）,如果其中一个到达末尾，则val1或val2赋值为0。然后，对两个数进行相加求余数，利用余数创建链表节点(lq)，并接在最先创建的链表(ll)后面，将节点ll先后指向下一个节点，同时计算val1+val2+temp的进位值。如果两个节点都已达到末尾，而此时还需进位值不为零（可以最后两个相加大于9），还需要创建一个节点来存储进位的值，并接在节点ll后面。</p>
<p><strong>代码：</strong></p>
<pre><code># Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def addTwoNumbers(self, l1, l2):
        &quot;&quot;&quot;
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        &quot;&quot;&quot;
        ll = ListNode(0)
        lp = ll
        temp = 0
        while l1 or l2:
            if l1 == None:
                val1 = 0
            else:
                val1 = l1.val
                l1 = l1.next
            if l2  == None:
                val2 = 0
            else:
                val2 = l2.val
                l2 = l2.next
            lq = ListNode((val1 + val2 + temp) % 10)
            ll.next = lq
            ll = ll.next
            temp = (val1 + val2 + temp) //10
            if l1 == None and l2 == None and temp != 0:
                lq = ListNode(temp)
                ll.next = lq
        return lp.next
</code></pre><p><strong>算法分析：</strong></p>
<p>时间复杂度：O(n)， 我们只遍历了包含有 nn 个元素的列表一次。在表中进行的每次查找只花费 O(1)O(1) 的时间。</p>
<p>空间复杂度：O(n)， 所需的额外空间取决于哈希表中存储的元素数量，该表最多需要存储 nn 个元素。</p>
<h2 id="无重复字符的最长子串"><a href="#无重复字符的最长子串" class="headerlink" title="无重复字符的最长子串"></a>无重复字符的最长子串</h2><p>给定一个字符串，找出不含有重复字符的最长子串的长度。</p>
<p>示例 1:</p>
<p>输入: “abcabcbb”<br>输出: 3<br>解释: 无重复字符的最长子串是 “abc”，其长度为 3。<br>示例 2:</p>
<p>输入: “bbbbb”<br>输出: 1<br>解释: 无重复字符的最长子串是 “b”，其长度为 1。<br>示例 3:</p>
<p>输入: “pwwkew”<br>输出: 3<br>解释: 无重复字符的最长子串是 “wke”，其长度为 3。<br>     请注意，答案必须是一个子串，”pwke” 是一个子序列 而不是子串。</p>
<h3 id="方法一：暴力法"><a href="#方法一：暴力法" class="headerlink" title="方法一：暴力法"></a>方法一：暴力法</h3><p>思路</p>
<p>逐个检查所有的子字符串，看它是否不含有重复的字符。</p>
<p>算法</p>
<p>假设我们有一个函数 boolean allUnique(String substring) ，如果子字符串中的字符都是唯一的，它会返回true，否则会返回false。 我们可以遍历给定字符串 s 的所有可能的子字符串并调用函数 allUnique。 如果事实证明返回值为true，那么我们将会更新无重复字符子串的最大长度的答案。</p>
<p>现在让我们填补缺少的部分：</p>
<p>为了枚举给定字符串的所有子字符串，我们需要枚举它们开始和结束的索引。假设开始和结束的索引分别为i和j。那么我们有 0≤i&lt;j≤n （这里的结束索引 j 是按惯例排除的）。因此，使用 i 从0到 n−1 以及 jj 从 i+1 到 n 这两个嵌套的循环，我们可以枚举出 s 的所有子字符串。</p>
<p>要检查一个字符串是否有重复字符，我们可以使用集合。我们遍历字符串中的所有字符，并将它们逐个放入 set 中。在放置一个字符之前，我们检查该集合是否已经包含它。如果包含，我们会返回 false。循环结束后，我们返回 true。</p>
<p><strong>代码：</strong></p>
<pre><code>class Solution:
    def lengthOfLongestSubstring(self, s):
        &quot;&quot;&quot;
        :type s: str
        :rtype: int
        &quot;&quot;&quot;

        def allUnique(s, start, end):
            st = set()
            for i in range(start,end):
                if s[i] in st:
                    return 0
                st.add(s[i])
            return 1

        l = len(s)
        ans = 0
        for i in range(0, l):
            for j in range(i+1, l+1):
                if(allUnique(s,i,j)):
                    ans = max(ans, j-i)
        return ans
</code></pre><h3 id="方法二：滑动窗口"><a href="#方法二：滑动窗口" class="headerlink" title="方法二：滑动窗口"></a>方法二：滑动窗口</h3><p><strong>代码：</strong></p>
<pre><code>class Solution:    
    def lengthOfLongestSubstring(self, s):
        &quot;&quot;&quot;
        :type s: str
        :rtype: int
        &quot;&quot;&quot;
        n = len(s)
        ans = i = j = 0
        st = set()
        while i &lt; n and j &lt; n:
            if s[j] in st:
                st.remove(s[i])
                i = i+1 
            else:
                st.add(s[j])
                j = j + 1
                ans = max(ans, j-i)
        return ans
</code></pre><h3 id="方法三：优化的滑动窗口"><a href="#方法三：优化的滑动窗口" class="headerlink" title="方法三：优化的滑动窗口"></a>方法三：优化的滑动窗口</h3><p><strong>代码：</strong></p>
<pre><code>class Solution:    
def lengthOfLongestSubstring(self, s):
    &quot;&quot;&quot;
    :type s: str
    :rtype: int
    &quot;&quot;&quot;
    n = len(s)
    ans = i = j = 0
    d = {} #将存放
    st = set()
    while j &lt; n:
        if s[j] in d.keys():
            i = max(i, d.get(s[j]))
        ans = max(ans, j-i+1)
        d[s[j]] = j + 1
        j = j + 1
    return ans  
</code></pre><h2 id="两个排序数组的中位数"><a href="#两个排序数组的中位数" class="headerlink" title="两个排序数组的中位数"></a>两个排序数组的中位数</h2><p>链接：<a href="https://leetcode-cn.com/problems/median-of-two-sorted-arrays/description/" target="_blank" rel="noopener">https://leetcode-cn.com/problems/median-of-two-sorted-arrays/description/</a></p>
<h1 id="二、数组"><a href="#二、数组" class="headerlink" title="二、数组"></a>二、数组</h1><h2 id="1-三数之和"><a href="#1-三数之和" class="headerlink" title="1.三数之和"></a>1.三数之和</h2><p>给定一个包含 n 个整数的数组 nums，判断 nums 中是否存在三个元素 a，b，c ，使得 a + b + c = 0 ？找出所有满足条件且不重复的三元组。</p>
<p>注意：答案中不可以包含重复的三元组。</p>
<p>例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4]，</p>
<p>满足要求的三元组集合为：<br>[<br>  [-1, 0, 1],<br>  [-1, -1, 2]<br>]</p>
<h3 id="方法一："><a href="#方法一：" class="headerlink" title="方法一："></a>方法一：</h3><p>该方案时间复杂度比方案二高</p>
<pre><code>class Solution:
    def threeSum(self, nums):
        &quot;&quot;&quot;
        :type nums: List[int]
        :rtype: List[List[int]]
        &quot;&quot;&quot;
        nums.sort()
        l = len(nums)
        a = []
        dict1 = {}
        for i in range(0,l):
            dict1[nums[i]] = i
        for i in range(0,l):
            for j in range(i+1,l):
                temp = -(nums[i] + nums[j])
                if temp in dict1.keys() and dict1[temp] &gt; i and dict1[temp] &gt; j:
                    b = [nums[i], nums[j], temp]
                    if b not in a:
                        a.append(b)

        return a
</code></pre><h3 id="方法二："><a href="#方法二：" class="headerlink" title="方法二："></a>方法二：</h3><p>该方案时间复杂度为O(n^2)</p>
<pre><code>class Solution:
    def threeSum(self, nums):
        &quot;&quot;&quot;
        :type nums: List[int]
        :rtype: List[List[int]]
        &quot;&quot;&quot;
        nums.sort()
        l = len(nums)
        a = []
        for i in range(0,l-2):
            if i &gt; 0 and nums[i] == nums[i-1]:
                continue
            l, r = i + 1, len(nums)-1
            while l &lt; r:
                s = nums[i] + nums[l] + nums[r]
                if s &lt; 0:
                    l += 1
                elif s &gt; 0:
                    r -= 1
                else:
                    a.append([nums[i], nums[l], nums[r]])
                    while l &lt; r and nums[l] == nums[l+1]:
                        l += 1
                    while l &lt; r and nums[r] == nums[r-1]:
                        r -= 1
                    l += 1
                    r -= 1
        return a
</code></pre><h2 id="2-最接近的三数之和"><a href="#2-最接近的三数之和" class="headerlink" title="2.最接近的三数之和"></a>2.最接近的三数之和</h2><p>给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数，使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。</p>
<p>例如，给定数组 nums = [-1，2，1，-4], 和 target = 1.</p>
<p>与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).</p>
<p><strong>代码</strong></p>
<pre><code>class Solution:
    def threeSumClosest(self, nums, target):
        &quot;&quot;&quot;
        :type nums: List[int]
        :type target: int
        :rtype: int
        &quot;&quot;&quot;
        ll = len(nums)
        nums.sort()
        result = nums[0] + nums[1] + nums[2]
        for i in range(ll-2):
            l, r = i + 1,ll-1
            while l &lt; r:
                sum1 = nums[i] + nums[l] + nums[r]
                if sum1 == target:
                    return sum1
                if abs(sum1 - target) &lt; abs(result - target):
                    result =  sum1
                if target &lt; sum1:
                    r -= 1
                elif target &gt; sum1:
                    l += 1
        return result
</code></pre><h2 id="3-四数之和"><a href="#3-四数之和" class="headerlink" title="3.四数之和"></a>3.四数之和</h2><p>给定一个包含 n 个整数的数组 nums 和一个目标值 target，判断 nums 中是否存在四个元素 a，b，c 和 d ，使得 a + b + c + d 的值与 target 相等？找出所有满足条件且不重复的四元组。</p>
<p>注意：</p>
<p>答案中不可以包含重复的四元组。</p>
<p>示例：</p>
<pre><code>给定数组 nums = [1, 0, -1, 0, -2, 2]，和 target = 0。

满足要求的四元组集合为：
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]
</code></pre><p><strong>代码</strong></p>
<pre><code>def fourSum(self, nums, target):
    def findNsum(nums, target, N, result, results):
        ll = len(nums)
        if  ll &lt; N or N &lt; 2 or target &lt; nums[0]*N or target &gt; nums[-1]*N: 
            return
        if N == 2: 
            l,r = 0,ll-1
            while l &lt; r:
                s = nums[l] + nums[r]
                if s == target:
                    results.append(result + [nums[l], nums[r]])
                    l += 1
                    while l &lt; r and nums[l] == nums[l-1]:
                        l += 1
                elif s &lt; target:
                    l += 1
                else:
                    r -= 1
        else: 
            for i in range(len(nums)-N+1):
                if i == 0 or (i &gt; 0 and nums[i-1] != nums[i]):
                    findNsum(nums[i+1:], target-nums[i], N-1, result+[nums[i]], results)

    results = []
    nums.sort()
    findNsum(nums, target, 4, [], results)
    return results
</code></pre><h2 id="4-删除排序数组中的重复项"><a href="#4-删除排序数组中的重复项" class="headerlink" title="4.删除排序数组中的重复项"></a>4.删除排序数组中的重复项</h2><p>给定一个排序数组，你需要在原地删除重复出现的元素，使得每个元素只出现一次，返回移除后数组的新长度。</p>
<p>不要使用额外的数组空间，你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。</p>
<p>示例 1:</p>
<pre><code>给定数组 nums = [1,1,2], 

函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。 

你不需要考虑数组中超出新长度后面的元素。
</code></pre><p>示例 2:</p>
<pre><code>给定 nums = [0,0,1,1,1,2,2,3,3,4],

函数应该返回新的长度 5, 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4。

你不需要考虑数组中超出新长度后面的元素。
</code></pre><p>说明:</p>
<p>为什么返回数值是整数，但输出的答案是数组呢?</p>
<p>请注意，输入数组是以“引用”方式传递的，这意味着在函数里修改输入数组对于调用者是可见的。</p>
<p>你可以想象内部操作如下:</p>
<pre><code>// nums 是以“引用”方式传递的。也就是说，不对实参做任何拷贝
int len = removeDuplicates(nums);

// 在函数里修改输入数组对于调用者是可见的。
// 根据你的函数返回的长度, 它会打印出数组中该长度范围内的所有元素。
for (int i = 0; i &lt; len; i++) {
    print(nums[i]);
}
</code></pre><h3 id="双指针法"><a href="#双指针法" class="headerlink" title="双指针法"></a>双指针法</h3><p>数组完成排序后，我们可以放置两个指针i和j ，其中i是慢指针，而j是快指针。只要nums[i]=nums[j]，我们就增加j 以跳过重复项。</p>
<p>当我们遇到 nums[j] \n  eq nums[i]时，跳过重复项的运行已经结束，因此我们必须把它（nums[j]）的值复制到nums[i+1]。然后递增i，接着我们将再次重复相同的过程，直到j 到达数组的末尾为止。</p>
<p><strong>代码：</strong></p>
<pre><code>class Solution:
def removeDuplicates(self, nums):
    &quot;&quot;&quot;
    :type nums: List[int]
    :rtype: int
    &quot;&quot;&quot;
    i = 0
    if len(nums) == 0:
        return 0
    for j in range(1, len(nums)):
        if nums[i] != nums[j]:
            i += 1
            nums[i] = nums[j]  
    return i + 1    
</code></pre><h2 id="5-移除元素"><a href="#5-移除元素" class="headerlink" title="5.移除元素"></a>5.移除元素</h2><p>给定一个数组 nums 和一个值 val，你需要原地移除所有数值等于 val 的元素，返回移除后数组的新长度。</p>
<p>不要使用额外的数组空间，你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。</p>
<p>元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。</p>
<p>示例 1:</p>
<pre><code>给定 nums = [3,2,2,3], val = 3,

函数应该返回新的长度 2, 并且 nums 中的前两个元素均为 2。

你不需要考虑数组中超出新长度后面的元素。
</code></pre><p>示例 2:</p>
<pre><code>给定 nums = [0,1,2,2,3,0,4,2], val = 2,

函数应该返回新的长度 5, 并且 nums 中的前五个元素为 0, 1, 3, 0, 4。

注意这五个元素可为任意顺序。

你不需要考虑数组中超出新长度后面的元素。
</code></pre><p>说明:</p>
<p>为什么返回数值是整数，但输出的答案是数组呢?</p>
<p>请注意，输入数组是以“引用”方式传递的，这意味着在函数里修改输入数组对于调用者是可见的。</p>
<p>你可以想象内部操作如下:</p>
<pre><code>// nums 是以“引用”方式传递的。也就是说，不对实参作任何拷贝
int len = removeElement(nums, val);

// 在函数里修改输入数组对于调用者是可见的。
// 根据你的函数返回的长度, 它会打印出数组中该长度范围内的所有元素。
for (int i = 0; i &lt; len; i++) {
    print(nums[i]);
}
</code></pre><h3 id="双指针法-1"><a href="#双指针法-1" class="headerlink" title="双指针法"></a>双指针法</h3><p>当我们遇到 nums[i] = val 时，我们可以将当前元素与最后一个元素进行交换，并释放最后一个元素。这实际上使数组的大小减少了 1。</p>
<p><strong>代码：</strong></p>
<pre><code>class Solution:
    def removeElement(self, nums, val):
        &quot;&quot;&quot;
        :type nums: List[int]
        :type val: int
        :rtype: int
        &quot;&quot;&quot;
        n = len(nums)
        i = 0
        while i &lt; n:
            if nums[i] == val:
                nums[i] = nums[n-1]
                n -= 1
            else:
                i += 1
        return n              
</code></pre><h2 id="6-下一排序"><a href="#6-下一排序" class="headerlink" title="6.下一排序"></a>6.下一排序</h2><p>实现获取下一个排列的函数，算法需要将给定数字序列重新排列成字典序中下一个更大的排列。</p>
<p>如果不存在下一个更大的排列，则将数字重新排列成最小的排列（即升序排列）。</p>
<p>必须原地修改，只允许使用额外常数空间。</p>
<p>以下是一些例子，输入位于左侧列，其相应输出位于右侧列。</p>
<pre><code>1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
</code></pre><p><strong>字典排序：</strong></p>
<p>对于数字1、2、3……n的排列，不同排列的先后关系是从左到右逐个比较对应的数字的先后来决定的。例如对于5个数字的排列 12354和12345，排列12345在前，排列12354在后。按照这样的规定，5个数字的所有的排列中最前面的是12345，最后面的是 54321。</p>
<h3 id="一遍扫描"><a href="#一遍扫描" class="headerlink" title="一遍扫描"></a>一遍扫描</h3><p><img src="https://i.imgur.com/tuXJeop.gif" alt=""></p>
<p><strong>代码：</strong></p>
<pre><code>class Solution:
    def nextPermutation(self, nums):
        &quot;&quot;&quot;
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        &quot;&quot;&quot;
        i = len(nums) - 2
        w hile (i &gt;= 0) and nums[i] &gt;= nums[i+1]:
            i -= 1
        if i &gt;= 0:
            j = len(nums) - 1
            while (j &gt;= 0) and nums[j] &lt;= nums[i]:
                j -= 1
            nums[i], nums[j] = nums[j], nums[i]

        k = len(nums) - 1
        i = i + 1
        while (i &lt; k):
            nums[i], nums[k] = nums[k], nums[i]
            i += 1
            k -= 1
</code></pre><h2 id="7-搜索旋转排序数组"><a href="#7-搜索旋转排序数组" class="headerlink" title="7.搜索旋转排序数组"></a>7.搜索旋转排序数组</h2><p>假设按照升序排序的数组在预先未知的某个点上进行了旋转。</p>
<p>( 例如，数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。</p>
<p>搜索一个给定的目标值，如果数组中存在这个目标值，则返回它的索引，否则返回 -1 。</p>
<p>你可以假设数组中不存在重复的元素。</p>
<p>你的算法时间复杂度必须是 O(log n) 级别。</p>
<p>示例 1:</p>
<pre><code>输入: nums = [4,5,6,7,0,1,2], target = 0
输出: 4
</code></pre><p>示例 2:</p>
<pre><code>输入: nums = [4,5,6,7,0,1,2], target = 3
输出: -1
</code></pre><p><strong>代码</strong></p>
<pre><code>class Solution:
    def search(self, nums, target):
        &quot;&quot;&quot;
        :type nums: List[int]
        :type target: int
        :rtype: int
        &quot;&quot;&quot;
        k = range(len(nums)) 
        d = dict(zip(nums,k))
        if target in d.keys():
            return d.get(target)
        else:
            return -1
</code></pre><h2 id="8-插入搜索位置"><a href="#8-插入搜索位置" class="headerlink" title="8.插入搜索位置"></a>8.插入搜索位置</h2><p>给定一个排序数组和一个目标值，在数组中找到目标值，并返回其索引。如果目标值不存在于数组中，返回它将会被按顺序插入的位置。</p>
<p>你可以假设数组中无重复元素。</p>
<p>示例 1:</p>
<pre><code>输入: [1,3,5,6], 5
输出: 2
</code></pre><p>示例 2:</p>
<pre><code>输入: [1,3,5,6], 2
输出: 1
</code></pre><p>示例 3:</p>
<pre><code>输入: [1,3,5,6], 7
输出: 4
</code></pre><p>示例 4:</p>
<pre><code>输入: [1,3,5,6], 0
输出: 0
</code></pre><p><strong>代码</strong></p>
<pre><code>class Solution:
def searchInsert(self, nums, target):
    &quot;&quot;&quot;
    :type nums: List[int]
    :type target: int
    :rtype: int
    &quot;&quot;&quot;
    if nums[len(nums)-1] &lt; target:
            return len(nums)
    for i in range(len(nums)):
        if nums[i] == target:
            return i
        if target &lt; nums[i]:
            return i
</code></pre><h2 id="9-组合总和"><a href="#9-组合总和" class="headerlink" title="9.组合总和"></a>9.组合总和</h2><p>给定一个无重复元素的数组 candidates 和一个目标数 target ，找出 candidates 中所有可以使数字和为 target 的组合。</p>
<p>candidates 中的数字可以无限制重复被选取。</p>
<p>说明：</p>
<p>所有数字（包括 target）都是正整数。<br>解集不能包含重复的组合。<br>示例 1:</p>
<pre><code>输入: candidates = [2,3,6,7], target = 7,
所求解集为:
[
  [7],
  [2,2,3]
]
</code></pre><p>示例 2:</p>
<pre><code>输入: candidates = [2,3,5], target = 8,
所求解集为:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]
</code></pre><p><strong>代码</strong></p>
<p>class Solution:<br>    def combinationSum(self, candidates, target):<br>        “””<br>        :type candidates: List[int]<br>        :type target: int<br>        :rtype: List[List[int]]<br>        “””<br>        if(target &lt; 0):<br>            return []<br>        if(target == 0):<br>            return [[]]<br>        return [[candidates[i]] + left<br>               for i in range(len(candidates))<br>               for left in self.combinationSum(candidates[i:], target - candidates[i])]</p>
<h2 id="10-缺失的第一个正数"><a href="#10-缺失的第一个正数" class="headerlink" title="10. 缺失的第一个正数"></a>10. 缺失的第一个正数</h2><p>给定一个未排序的整数数组，找出其中没有出现的最小的正整数。</p>
<p>示例 1:</p>
<pre><code>输入: [1,2,0]
输出: 3
</code></pre><p>示例 2:</p>
<pre><code>输入: [3,4,-1,1]
输出: 2
</code></pre><p>示例 3:</p>
<pre><code>输入: [7,8,9,11,12]
输出: 1
</code></pre><p>说明:</p>
<p>你的算法的时间复杂度应为O(n)，并且只能使用常数级别的空间。</p>
<p><strong>代码</strong></p>
<pre><code>class Solution:
    def firstMissingPositive(self, nums):
        &quot;&quot;&quot;
        :type nums: List[int]
        :rtype: int
        &quot;&quot;&quot;
        if len(nums) == 0:
            return 1
        dict1 = dict(zip(nums, range(len(nums))))
        for i in range(1,max(nums)+1):
            if i in dict1.keys():
                continue
            return i
        return max(nums)+1
</code></pre><h2 id="11-接雨水"><a href="#11-接雨水" class="headerlink" title="11. 接雨水"></a>11. 接雨水</h2><p>给定 n 个非负整数表示每个宽度为 1 的柱子的高度图，计算按此排列的柱子，下雨之后能接多少雨水。</p>
<p><img src="https://i.imgur.com/NkFDJCn.png" alt=""></p>
<p>上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图，在这种情况下，可以接 6 个单位的雨水（蓝色部分表示雨水）。 感谢 Marcos 贡献此图。</p>
<p>示例:</p>
<pre><code>输入: [0,1,0,2,1,0,1,3,2,1,2,1]
输出: 6
</code></pre><p><strong>代码</strong></p>
<pre><code>class Solution:
    def trap(self, height):
        &quot;&quot;&quot;
        :type height: List[int]
        :rtype: int
        &quot;&quot;&quot;
        l = len(height)
        if l == 0:
            return 0
        total = 0
        left_max = [0]*l
        right_max = [0]*l
        left_max[0] = height[0]
        for i in range(1, l):
            left_max[i] = max(height[i], left_max[i-1])

        right_max[l-1] = height[l-1]
        for i in range(l-2, -1, -1):
            right_max[i] = max(height[i], right_max[i+1])
        for i in range(0,l-1):
            total += min(left_max[i],right_max[i]) - height[i]
        return total
</code></pre><h2 id="12-跳跃游戏Ⅱ"><a href="#12-跳跃游戏Ⅱ" class="headerlink" title="12. 跳跃游戏Ⅱ"></a>12. 跳跃游戏Ⅱ</h2><p>给定一个非负整数数组，你最初位于数组的第一个位置。</p>
<p>数组中的每个元素代表你在该位置可以跳跃的最大长度。</p>
<p>你的目标是使用最少的跳跃次数到达数组的最后一个位置。</p>
<p>示例:</p>
<pre><code>输入: [2,3,1,1,4]
输出: 2
</code></pre><p>解释: 跳到最后一个位置的最小跳跃数是 2。<br>     从下标为 0 跳到下标为 1 的位置，跳 1 步，然后跳 3 步到达数组的最后一个位置。<br>说明:</p>
<p>假设你总是可以到达数组的最后一个位置。</p>
<p><strong>代码</strong></p>
<pre><code>class Solution:
    def jump(self, nums):
        &quot;&quot;&quot;
        Greedy implementation maximizing the length of each jump.
        :type nums: List[int]
        :rtype: int
        &quot;&quot;&quot;
        current_index = 0
        target_index = len(nums) - 1 
        total_jumps = 0

        while current_index &lt; target_index:
            total_jumps += 1
            jump_range = range(current_index, current_index + nums[current_index] + 1) 
            if target_index in jump_range:
                break

            next_index = current_index
            for next_index_candidate in jump_range:               
                candidate_jump_destination = next_index_candidate + nums[next_index_candidate]
                next_jump_destination = next_index + nums[next_index]
                if next_jump_destination &lt; candidate_jump_destination :
                    next_index = next_index_candidate

            current_index = next_index

        return total_jumps
</code></pre><h2 id="13-图像旋转"><a href="#13-图像旋转" class="headerlink" title="13. 图像旋转"></a>13. 图像旋转</h2><p>给定一个 n × n 的二维矩阵表示一个图像。</p>
<p>将图像顺时针旋转 90 度。</p>
<p>说明：</p>
<p>你必须在原地旋转图像，这意味着你需要直接修改输入的二维矩阵。请不要使用另一个矩阵来旋转图像。</p>
<p>示例 1:</p>
<pre><code>给定 matrix = 
[
  [1,2,3],
  [4,5,6],
  [7,8,9]
],

原地旋转输入矩阵，使其变为:
[
  [7,4,1],
  [8,5,2],
  [9,6,3]
]
</code></pre><p>示例 2:</p>
<pre><code>给定 matrix =
[
  [ 5, 1, 9,11],
  [ 2, 4, 8,10],
  [13, 3, 6, 7],
  [15,14,12,16]
], 

原地旋转输入矩阵，使其变为:
[
  [15,13, 2, 5],
  [14, 3, 4, 1],
  [12, 6, 8, 9],
  [16, 7,10,11]
]
</code></pre><p><strong>代码</strong></p>
<pre><code>class Solution:
    def rotate(self, matrix):
        &quot;&quot;&quot;
        :type matrix: List[List[int]]
        :rtype: void Do not return anything, modify matrix in-place instead.
        &quot;&quot;&quot;
        n = len(matrix)-1
        #交换第i行和第n-i行
        for i in range(len(matrix)//2):
                matrix[i][:], matrix[n-i][:] = matrix[n-i][:], matrix[i][:]
        #将矩阵进行装置
        for i in range(len(matrix)):
            for j in range(i+1, len(matrix)):
                matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
</code></pre><h2 id="14-最大子序和"><a href="#14-最大子序和" class="headerlink" title="14. 最大子序和"></a>14. 最大子序和</h2><p>给定一个整数数组 nums ，找到一个具有最大和的连续子数组（子数组最少包含一个元素），返回其最大和。</p>
<p>示例:</p>
<pre><code>输入: [-2,1,-3,4,-1,2,1,-5,4],
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大，为 6。
</code></pre><p>进阶:</p>
<p>如果你已经实现复杂度为 O(n) 的解法，尝试使用更为精妙的分治法求解。</p>
<p><strong>C++实现</strong></p>
<pre><code>class Solution {
public:
    int maxSubArray(vector&lt;int&gt;&amp; nums) {
        int n = nums.size();
        int *dp = new int[n];
        dp[0] = nums[0];
        int max = dp[0];
        for (int i = 1; i &lt; n; i++)
        {
            dp[i] = nums[i] + (dp[i-1] &gt; 0 ? dp[i-1] : 0);
            max = max &gt; dp[i] ? max : dp[i];
        }
        return max;
    }
};
</code></pre><h2 id="15-螺旋矩阵"><a href="#15-螺旋矩阵" class="headerlink" title="15 螺旋矩阵"></a>15 螺旋矩阵</h2><p>给定一个包含 m x n 个元素的矩阵（m 行, n 列），请按照顺时针螺旋顺序，返回矩阵中的所有元素。</p>
<p>示例 1:</p>
<pre><code>输入:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
</code></pre><p>示例 2:</p>
<pre><code>输入:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]
</code></pre><p><strong>思路</strong></p>
<p>一层一层输出，先输出第一行，最后一列，最后一行，第一列。然后进入第二层，采用通过的顺序输出。</p>
<p><img src="https://i.imgur.com/RRuWyQ4.png" alt=""></p>
<p><strong>C++实现</strong></p>
<pre><code>class Solution {
public:
    vector&lt;int&gt; spiralOrder(vector&lt;vector&lt;int&gt;&gt;&amp; matrix) {
        if (matrix.empty()) return {};
        int j = 0;
        int r1 = 0;
        int r2 = matrix.size()-1;
        int c1 = 0;
        int c2 = matrix[0].size()-1;
        int totalnums = (r2+1) * (c2+1);
        vector&lt;int&gt; p(totalnums);
        int k = 0;
        while (r1 &lt;= r2 and c1 &lt;= c2)
        {
            for (int i = c1; i &lt;= c2; i++) p[k++] = matrix[r1][i];
            for (int j = r1 + 1; j &lt;= r2; j++) p[k++] = matrix[j][c2];
            if (r1 &lt; r2 &amp;&amp; c1 &lt; c2)
            {
                cout &lt;&lt; &apos;1&apos; &lt;&lt; endl;
                for (int i = c2 - 1; i &gt; c1; i--) p[k++] = matrix[r2][i];
                for (int j = r2; j &gt; r1; j--) p[k++] = matrix[j][c1];
            }
            r1++;
            r2--;
            c1++;
            c2--;  
        }
        return p;
    }
};
</code></pre><h2 id="16-跳跃游戏"><a href="#16-跳跃游戏" class="headerlink" title="16 跳跃游戏"></a>16 跳跃游戏</h2><p>给定一个非负整数数组，你最初位于数组的第一个位置。</p>
<p>数组中的每个元素代表你在该位置可以跳跃的最大长度。</p>
<p>判断你是否能够到达最后一个位置。</p>
<p>示例 1:</p>
<pre><code>输入: [2,3,1,1,4]
输出: true
解释: 从位置 0 到 1 跳 1 步, 然后跳 3 步到达最后一个位置。
</code></pre><p>示例 2:</p>
<pre><code>输入: [3,2,1,0,4]
输出: false
解释: 无论怎样，你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 ， 所以你永远不可能到达最后一个位置。
</code></pre>
      
    </div>
    
    
    

    
      <div>
        <div id="wechat_subscriber" style="display: block; padding: 10px 0; margin: 20px auto; width: 100%; text-align: center">
    <img id="wechat_subscriber_qcode" src="/images/wechat-qcode.jpg" alt="zxp wechat" style="width: 200px; max-width: 100%;"/>
    <div>欢迎关注微信公众号！</div>
</div>

      </div>
    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div></div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/WeChatpay.jpg" alt="zxp 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/Alipay.jpg" alt="zxp 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    zxp
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://zxpgo.github.io/2018/08/22/LeetCode算法题目/" title="LeetCode算法题目">https://zxpgo.github.io/2018/08/22/LeetCode算法题目/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tag/面试题目/" rel="tag"># 面试题目</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div id="needsharebutton-postbottom">
            <span class="btn">
              <i class="fa fa-share-alt" aria-hidden="true"></i>
            </span>
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/08/22/进制相互转换/" rel="next" title="进制介绍以及相互转换">
                <i class="fa fa-chevron-left"></i> 进制介绍以及相互转换
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/08/22/python2.7和python3.6安装以及问题解决/" rel="prev" title="Python2.7和Python3.6安装以及文件解决">
                Python2.7和Python3.6安装以及文件解决 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zODgxNC8xNTM0Mg=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.gif"
                alt="zxp" />
            
              <p class="site-author-name" itemprop="name">zxp</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">176</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">48</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://blog.csdn.net/qq_25774883" target="_blank" title="CSDN">
                      
                        <i class="fa fa-fw fa-globe"></i>CSDN</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/zxpgo/zxpgo" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-globe"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.linkedin.com/feed/" target="_blank" title="LinkedIn">
                      
                        <i class="fa fa-fw fa-globe"></i>LinkedIn</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="1165772354@qq.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                友情链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="http://theme-next.iissnan.com" title="Next主题" target="_blank">Next主题</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://blog.rexking6.top" title="青爷博客" target="_blank">青爷博客</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://me.csdn.net/download/qq_25774883" title="CSDN下载" target="_blank">CSDN下载</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.livere.com/" title="来必力" target="_blank">来必力</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://tongji.baidu.com/web/welcome/login" title="百度统计" target="_blank">百度统计</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://leancloud.cn/" title="LeanCloud" target="_blank">LeanCloud</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://ibruce.info/2015/04/04/busuanzi/" title="不蒜子" target="_blank">不蒜子</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://leetcode-cn.com/" title="LeetCode" target="_blank">LeetCode</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#两数之和"><span class="nav-number">1.</span> <span class="nav-text">两数之和</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#两数相加"><span class="nav-number">2.</span> <span class="nav-text">两数相加</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#无重复字符的最长子串"><span class="nav-number">3.</span> <span class="nav-text">无重复字符的最长子串</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#方法一：暴力法"><span class="nav-number">3.1.</span> <span class="nav-text">方法一：暴力法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#方法二：滑动窗口"><span class="nav-number">3.2.</span> <span class="nav-text">方法二：滑动窗口</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#方法三：优化的滑动窗口"><span class="nav-number">3.3.</span> <span class="nav-text">方法三：优化的滑动窗口</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#两个排序数组的中位数"><span class="nav-number">4.</span> <span class="nav-text">两个排序数组的中位数</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#二、数组"><span class="nav-number"></span> <span class="nav-text">二、数组</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-三数之和"><span class="nav-number">1.</span> <span class="nav-text">1.三数之和</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#方法一："><span class="nav-number">1.1.</span> <span class="nav-text">方法一：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#方法二："><span class="nav-number">1.2.</span> <span class="nav-text">方法二：</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-最接近的三数之和"><span class="nav-number">2.</span> <span class="nav-text">2.最接近的三数之和</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-四数之和"><span class="nav-number">3.</span> <span class="nav-text">3.四数之和</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-删除排序数组中的重复项"><span class="nav-number">4.</span> <span class="nav-text">4.删除排序数组中的重复项</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#双指针法"><span class="nav-number">4.1.</span> <span class="nav-text">双指针法</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-移除元素"><span class="nav-number">5.</span> <span class="nav-text">5.移除元素</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#双指针法-1"><span class="nav-number">5.1.</span> <span class="nav-text">双指针法</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6-下一排序"><span class="nav-number">6.</span> <span class="nav-text">6.下一排序</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#一遍扫描"><span class="nav-number">6.1.</span> <span class="nav-text">一遍扫描</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#7-搜索旋转排序数组"><span class="nav-number">7.</span> <span class="nav-text">7.搜索旋转排序数组</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#8-插入搜索位置"><span class="nav-number">8.</span> <span class="nav-text">8.插入搜索位置</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#9-组合总和"><span class="nav-number">9.</span> <span class="nav-text">9.组合总和</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#10-缺失的第一个正数"><span class="nav-number">10.</span> <span class="nav-text">10. 缺失的第一个正数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#11-接雨水"><span class="nav-number">11.</span> <span class="nav-text">11. 接雨水</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#12-跳跃游戏Ⅱ"><span class="nav-number">12.</span> <span class="nav-text">12. 跳跃游戏Ⅱ</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#13-图像旋转"><span class="nav-number">13.</span> <span class="nav-text">13. 图像旋转</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#14-最大子序和"><span class="nav-number">14.</span> <span class="nav-text">14. 最大子序和</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#15-螺旋矩阵"><span class="nav-number">15.</span> <span class="nav-text">15 螺旋矩阵</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#16-跳跃游戏"><span class="nav-number">16.</span> <span class="nav-text">16 跳跃游戏</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div>
<script async src="https//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_pv" style='display:none'>
    本站总访问量 <span id="busuanzi_value_site_pv"></span> 
    <span class="post-meta-divider">|</span>
</span>
<span id="busuanzi_container_site_uv" style='display:none'>
    访问人数 <span id="busuanzi_value_site_uv"></span>
</span>
</div>


<script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<div class="copyright">&copy; 2018-8 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-"></i> Power by 
  </span>
  <span class="author" itemprop="copyrightHolder">zxp</span>
  
  
</div>









        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    
      <div id="needsharebutton-float">
        <span class="btn">
          <i class="fa fa-share-alt" aria-hidden="true"></i>
        </span>
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  




  
  <div id="lv-container" data-uid="MTAyMC8zODgxNC8xNTM0Mg==">
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
	</div>
  











  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("2AyV3DKioBSdoryrFLRohzjB-gzGzoHsz", "XynedcHyJCVCrTfbD4yYnodo");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
      pbOptions = {};
      
          pbOptions.iconStyle = "default";
      
          pbOptions.boxForm = "vertical";
      
          pbOptions.position = "top";
      
          pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
      flOptions = {};
      
          flOptions.iconStyle = "box";
      
          flOptions.boxForm = "horizontal";
      
          flOptions.position = "middleRight";
      
          flOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-float', flOptions);
    
  </script>

  

  
  


  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.4"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.4"></script>


  
  <script type="text/javascript" src="/js/src/exturl.js?v=5.1.4"></script>


  
  
  	 <!-- custom analytics part create by xiamo -->
<script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
<script>AV.initialize("2AyV3DKioBSdoryrFLRohzjB-gzGzoHsz", "XynedcHyJCVCrTfbD4yYnodo");</script>
<script>
function showTime(Counter) {
	var query = new AV.Query(Counter);
	$(".leancloud_visitors").each(function() {
		var url = $(this).attr("id").trim();
		query.equalTo("url", url);
		query.find({
			success: function(results) {
				if (results.length == 0) {
					var content = $(document.getElementById(url)).text() + ' 0';
					$(document.getElementById(url)).text(content);
					return;
				}
				for (var i = 0; i < results.length; i++) {
					var object = results[i];
					var content = $(document.getElementById(url)).text() + ' ' + object.get('time');
					$(document.getElementById(url)).text(content);
				}
			}
		});

	});
}

</script>
  
</body>
</html>
